import threading
import time

condition = threading.Condition()
running_flag = True
cond_flag = False


def worker_thread(id, condition):
    global running_flag
    global cond_flag
    while running_flag == True:
        with condition:
            while cond_flag == False:
                print(f"Worker {id} is waiting...")
                condition.wait()
            print(f"Worker {id} received the signal and is finishing its job.")
            cond_flag = False
            time.sleep(1)

def get_cmd(condition):
    global running_flag
    global cond_flag
    while True:
        help="""
按1: 发送notify
按2: 发送notify_all
按q: 退出程序
"""
        cmd = input(help)
        if cmd == "1":
            cond_flag = True
            with condition:
                condition.notify()
        elif cmd == "2":
            cond_flag = True
            with condition:
                condition.notify_all()
        elif cmd == "q":
            print("退出程序")
            running_flag = False
            cond_flag = True
            with condition:
                condition.notify_all()
            time.sleep(1)
            # NOTE: 通知两次原因,
            # 1.是因为第一个thread 退出时,设置cond_flag = False;
            # 2.第二个thread 再被唤醒, 但conf_flag已经为 False
            cond_flag = True
            with condition:
                condition.notify_all()
            break
        else:
            print(f"不支持命令: {cmd}")


def main_thread():
    t1 = threading.Thread(target=worker_thread, args=(1, condition))
    t1.start()
    t2 = threading.Thread(target=worker_thread, args=(2, condition))
    t2.start()
    get_cmd(condition)

    # 等待所有工作线程完成
    t1.join()
    t2.join()


if __name__ == "__main__":
    main_thread()
